package com.engine.qz.service.impl;

import com.api.hrm.bean.FieldItem;
import com.api.hrm.util.FieldType;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.qz.entity.CustomTemplateVo;
import com.engine.qz.entity.CustomTranscerDataVo;

import com.engine.qz.entity.EditTableColumn;
import com.engine.qz.entity.TemplateFieldsPo;
import com.engine.qz.service.CustomRosterService;
import com.engine.qz.service.HrmCustomTemplateService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.conn.RecordSet;
import weaver.hrm.User;

import java.util.*;
import java.util.stream.Collectors;




/**
 * @Author Apple
 * @Date 2025/2/24 11:08
 * @Description:
 * @Version 1.0
 */
public class HrmCustomTemplateServiceImpl extends Service implements HrmCustomTemplateService {


    private CustomRosterService getService(User user) {
        return ServiceUtil.getService(CustomRosterServiceImpl.class,user);
    }

    @Override
    public CustomTranscerDataVo getCustomTransferData(Map<String, Object> params) {

        //1.所有可查看字段
        //LinkedList<TemplateFieldsPo> transferDatas = rosterList();
        LinkedList<TemplateFieldsPo> transferDatas = getService(user).customFieldMap();

        //2.存在模板 且已经选择的字段
        LinkedList<CustomTemplateVo> customTemplate = getCustomTemplate();
        Optional<CustomTemplateVo> result = customTemplate.stream()
                .filter(vo -> vo.getIsused() == 1)
                .findFirst();

        LinkedList<String>  transferKeys = new LinkedList<>();
        CustomTemplateVo customTemplateVo = new CustomTemplateVo();
        if (result.isPresent()) {
            customTemplateVo = result.get();
            transferKeys.addAll(Arrays.asList(customTemplateVo.getTemplateFields().split(",")));

        } else {
            //(todo 无模板或不存在启用模板)


        }
        return CustomTranscerDataVo.builder().templateId(customTemplateVo.getKey()).transferDatas(transferDatas).transferKeys(transferKeys).build();
    }

    @Override
    public LinkedList<CustomTemplateVo> getCustomTemplate() {

        RecordSet rs = new RecordSet();
        LinkedList<CustomTemplateVo> customTemplateVos = new LinkedList<>();
        rs.executeQuery("select id,templateName,templateFields,isused,belongto,modedatacreatedate from uf_custom_template \n" +
                "where belongto = ? order by id asc",user.getUID());

        while (rs.next()) {
            customTemplateVos.add(CustomTemplateVo.builder()
                    .key(Util.null2String(rs.getString("id")))
                    .showname(Util.null2String(rs.getString("templateName")))
                    .templateFields(Util.null2String(rs.getString("templateFields")))
                    .isused(Util.getIntValue(rs.getString("isused")))
                    .belongto(Util.getIntValue(rs.getString("belongto")))
                    .modedatacreatedate(Util.null2String(rs.getString("modedatacreatedate")))
                    .build());
        }

        //todo 没有模板或者模版都没启用

        return customTemplateVos;
    }

    @Override
    public Map<String, Object> addCustomTemplate(Map<String, Object> params) {

        String customTemplateName = Util.null2String(params.get("showname"));
        String fields = Util.null2String(params.get("fields"));

        String currentDate = TimeUtil.getCurrentDateString();
        String currentTime = TimeUtil.getOnlyCurrentTimeString();
        int uid = user.getUID();
        String uuid =  UUID.randomUUID().toString();
        Map<String, Object> datas = new HashMap<>(4);

        RecordSet rs = new RecordSet();
        String templateId = "";
        boolean result = rs.executeUpdate("insert into uf_custom_template(templateName,templateFields,isused,belongto,modedatacreatedate,modedatacreatetime," +
                " modedatacreater,modeuuid) values(?,?,?,?,?,?,?,?)", customTemplateName, fields, 0, uid, currentDate, currentTime, uid, uuid);
        if (result) {
            rs.executeQuery("select id from uf_custom_template where modeuuid = ?",uuid);
            if (rs.next()) {
                templateId = Util.null2String(rs.getString("id"));
            }
        }
        datas.put("templateId",templateId);
        datas.put("customTemplates",getCustomTemplate());


        return datas;
    }

    @Override
    public void updateCustomTemplateFields(Map<String, Object> params) {

        String templateId = Util.null2String(params.get("templateId"));
        String fields = Util.null2String(params.get("fields"));

        RecordSet rs = new RecordSet();
        //1.更新当前用户该方案数据
        boolean flag = rs.executeUpdate("update uf_custom_template set templateFields = '" + fields + "',isused = 1 where id = ?", templateId);

        //2.更新当前用户其它方案为未启用
        if (flag) {
            rs.executeUpdate("update uf_custom_template set isused = 0 where belongto = ? and id <> ?",user.getUID(),templateId);
        }

    }

    @Override
    public LinkedList<String> getTemplateSelectKeys(String templateId) {
        LinkedList<CustomTemplateVo> customTemplateList = getCustomTemplate();
        CustomTemplateVo customTemplate = customTemplateList.stream()
                .filter(item -> templateId.equals(item.getKey()))
                .findFirst()
                .get();

        return new LinkedList<>(Arrays.asList(customTemplate.getTemplateFields().split(",")));
    }

    @Override
    public Map<String, Object> customTemplateTable() {

        Map<String, Object> result = new HashMap<>(4);

        List<EditTableColumn> columns = new ArrayList<>();
        columns.add(EditTableColumn.builder().viewAttr(3).fieldName("templateName").fieldNameDesc("模板名称").fieldType(FieldType.INPUT).build());
        columns.add(EditTableColumn.builder().viewAttr(1).fieldName("modedatacreatedate").fieldNameDesc("创建日期").fieldType(FieldType.INPUT).build());

        List<Map<String, Object>> lsCol = new ArrayList<>();
        Map<String, Object> col;

        int width = 100 / columns.size();
        for (EditTableColumn editTableColumn : columns) {
            String tmpkey = editTableColumn.getFieldName();
            col = new HashMap<>(8);
            col.put("title", editTableColumn.getFieldNameDesc());
            col.put("key", tmpkey);
            col.put("dataIndex", tmpkey);
            col.put("com", getFieldDetailInfo(editTableColumn,width));
            col.put("width", width + "%");

            lsCol.add(col);
        }
        result.put("columns",lsCol);
        LinkedList<CustomTemplateVo> templateVos = getCustomTemplate();
        List<Map<String, Object>> collect = templateVos.stream().map(item -> {
            Map<String, Object> resultMap = new HashMap<>(8);
            resultMap.put("id", item.getKey());
            resultMap.put("templateName", item.getShowname());
            resultMap.put("modedatacreatedate", item.getModedatacreatedate());
            return resultMap;
        }).collect(Collectors.toList());

        result.put("datas", collect);
        return result;
    }

    @Override
    public void saveCustomTemplateTable(Map<String, Object> params) {
        LinkedList<CustomTemplateVo> customTemplateList = getCustomTemplate();
        LinkedList<String> keyList = customTemplateList.stream()
                .map(CustomTemplateVo::getKey)
                .collect(Collectors.toCollection(LinkedList::new));
        int rowNum = Util.getIntValue((String) params.get("rownum"));
        RecordSet rs = new RecordSet();
        for (int i = 0; i < rowNum; i++) {
            String recordIndex = "_" + i;
            String id = Util.null2String(params.get("id" + recordIndex));
            String templateName = Util.null2String(params.get("templateName" + recordIndex));
            rs.executeUpdate("update uf_custom_template set templateName = ? where id = ?",templateName,id);
            keyList.remove(id);
        }

        if (CollectionUtils.isNotEmpty(keyList)) {
            String value = StringUtils.join(keyList,",");
            rs.executeUpdate("delete from uf_custom_template where id in ("+value+")");
        }
    }

    private List<FieldItem> getFieldDetailInfo(EditTableColumn column,int width) {
        List<FieldItem> ls = new ArrayList<>();
        FieldItem fieldItem = new FieldItem();
        fieldItem.setType(column.getFieldType());
        fieldItem.setKey(column.getFieldName());
        fieldItem.setViewAttr(column.getViewAttr());
        switch (fieldItem.getType()) {
            case INPUT:
                Map<String, Object> otherParams = new HashMap<>(2);
                otherParams.put("inputType","multilang");
                fieldItem.setOtherParams(otherParams);
                break;
            default:
                break;
        }

        fieldItem.setWidth(width + "%");
        ls.add(fieldItem);
        return ls;
    }


    private LinkedList<TemplateFieldsPo> rosterList() {

        LinkedList<TemplateFieldsPo> templateFields = new LinkedList<>();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id,chinese,dataName from uf_roster_field order by id asc");
        while (rs.next()) {
            templateFields.add(TemplateFieldsPo.builder()
                    .id(Util.null2String(rs.getString("id")))
                    .fieldName(Util.null2String(rs.getString("chinese")))
                    .fieldDataName(Util.null2String(rs.getString("dataName")))
                    .build());
        }

        return templateFields;
    }


}
